/*
 *  Copyright 2012 SerGenis. All rights reserved.
 */
package com.sergenis.beans;

import com.sergenis.swing.ListViewModel;
import com.sergenis.util.SerialClone;
import java.util.Collections;
import java.util.Collection;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author SerGenis
 */
public abstract class AbstractListSingleBinding<E>
    extends AbstractBean
    implements ListSelectionListener {

    public AbstractListSingleBinding(ListSelectionModel selectionModel) {
	this(selectionModel, Collections.EMPTY_LIST);
    }

    public AbstractListSingleBinding(ListSelectionModel selectionModel, Collection<E> elements) {
	selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	selectionModel.addListSelectionListener(this);
	this.selectionModel = selectionModel;
	this.listModel = new ListViewModel<E>(elements);
    }
    protected E active = null;
    protected E backup = null;
    protected int indexActive = -1;
    protected int indexBackup = -1;
    ;
    protected final ListSelectionModel selectionModel;
    protected ListViewModel<E> listModel;

    public abstract void setElements(Collection<E> c);

    //<editor-fold defaultstate="collapsed" desc="Getters & Setters">
    public E getActive() {
	return active;
    }

    protected void setActive(E active) {
	E oldActive = this.active;
	this.active = active;
	firePropertyChange("active", oldActive, this.active);
    }

    public int getIndexActive() {
	return indexActive;
    }

    protected void setIndexActive(int indexActive) {
	int oldIndexActive = this.indexActive;
	this.indexActive = indexActive;
	firePropertyChange("indexActive", oldIndexActive, this.indexActive);
    }

    public void makeBackup() {
	synchronized ( this ) {
	    setIndexBackup(this.indexActive);
	    setBackup(SerialClone.clone(getActive()));
	}
    }

    public final void restoreBackup() {
	synchronized ( this ) {
	    listModel.set(indexBackup, backup);
	    discardBackup();
	}
    }

    public final void discardBackup() {
	setBackup(null);
	setIndexBackup(-1);
    }

    public E getBackup() {
	return backup;
    }

    private void setBackup(E backup) {
	E oldBackup = this.backup;
	this.backup = backup;
	firePropertyChange("backup", oldBackup, this.backup);
    }

    public int getIndexBackup() {
	return indexBackup;
    }

    private void setIndexBackup(int indexBackup) {
	int oldIndexBackup = this.indexBackup;
	this.indexBackup = indexBackup;
	firePropertyChange("indexBackup", oldIndexBackup, this.indexBackup);
    }

    //<editor-fold defaultstate="collapsed" desc="Getter & Setter (selectionModel, listmodel)">
    public ListViewModel<E> getListModel() {
	return listModel;
    }

    public ListSelectionModel getSelectionModel() {
	return selectionModel;
    }
    //</editor-fold>
    //</editor-fold>
}
